import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import moment from 'moment';
import {indexOf} from 'lodash'
import { Row, Col, Card, Form, Select, Button, message, Popconfirm, Tabs, Table, Upload, notification, Dropdown, Menu, Tooltip,
  Alert,
  Icon, } from 'antd';

const TabPane = Tabs.TabPane;
import { convertProjectCode } from './components/toolkit';
import {tableChangePagination} from './components/Pagination'
import TeamInfoForm from './components/TeamForm'
import styles from './TableList.less';
import { isNull } from 'util';

import { generateChouqianTable } from './components/ChouqianTable';
import { generateTreeTable } from './components/ChouqianTree'

const FormItem = Form.Item;
const { Option } = Select;

@connect(({ zubie,phase, loading }) => ({
  zubie,phase,
  loading: loading.models.zubie,
}))
@Form.create()
export default class SignTable extends PureComponent {
  state = {
    modalVisible: false,
    expandForm: false,
    selectedRows: [],
    formValues: {},
  };

  componentDidMount() {
    const { dispatch, location } = this.props;
    const pathArray = location.pathname.split('/');
    const id = pathArray[3];
    this.setState({
      id,
    });

    dispatch({
      type: 'zubie/clean',
      payload: {},
    });

    dispatch({
      type: 'gameList/findById',
      payload: id,
      callback: () => {
        dispatch({
          type: 'zubie/queryAllZubieForGame',
          callback:()=>{
            const {zubie: { curZubie, zubieList }} = this.props;
            //console.log(curZubie)
            if(!curZubie){
              return
            }
            const zubieMap = zubieList.map( value =>{
              return value.code
            })
            if(indexOf(zubieMap, curZubie)>-1){
              this.onSelectZubie(curZubie);
            }else{
              this.props.dispatch({
                type: 'zubie/changeState',
                payload: {
                  curZubie: null,
                  curZubieObj: {},
                },
              });
            }
          }
        });
        
      },
    });
  }

  onSelectZubie = value => {

    this.setState({
      curPhase: null,
    });

    this.props.dispatch({
      type: 'zubie/changeState',
      payload: {
        curZubie: value,
      },
    });

    this.props.dispatch({
      type: 'zubie/queryZubieByCode',
      payload: value,
    });

    this.props.dispatch({
      type: 'zubie/queryPhase',
      payload: value,
      callback: () => {
        const phaseMap = {}
        this.props.zubie.phaseList.map(element => {
          phaseMap[element.code] = element
        })

        this.setState({ phaseMap: phaseMap })
      }
    });

    this.props.dispatch({
      type: 'zubie/queryZhixuForChouqian',
      payload: {
        zubieCode: value,
      },
    });

    // this.props.dispatch({
    //   type: 'zubie/queryFenzuListForZubie',
    //   payload: {
    //     zubieCode: value,
    //   },
    // });

    // this.props.dispatch({
    //   type: 'zubie/queryChouqian',
    //   payload: {
    //     zubieCode: value,
    //   },
    // });
  };

  onSelectPhase = value => {
    this.setState({
      curPhase: value,
    });
    // this.props.dispatch({
    //   type: 'zubie/queryFenzuListForZubie',
    //   payload: {
    //     zubieCode: this.props.zubie.curZubie,
    //     phaseCode: value,
    //   },
    // });

    // this.props.dispatch({
    //   type: 'zubie/queryChouqian',
    //   payload: {
    //     zubieCode: this.props.zubie.curZubie,
    //     phaseCode: value,
    //   },
    // });
  };

  autoChouqian = () => {
    this.props.dispatch({
      type: 'zubie/autoChouqian',
      payload: {
        zubieCode: this.props.zubie.curZubie,
        phaseCode: this.state.curPhase ? this.state.curPhase : null,
      },
      callback: () => {
        message.success('自动抽签完成')
        this.props.dispatch({
          type: 'zubie/queryPhase',
          payload: this.props.zubie.curZubie,
          callback: () => {
            const phaseMap = {}
            this.props.zubie.phaseList.map(element => {
              phaseMap[element.code] = element
            })
            this.setState({ phaseMap: phaseMap })
          }
        });
        // this.props.dispatch({
        //   type: 'zubie/findPhaseTeamByZubie',
        //   payload: {
        //     zubieCode: this.props.zubie.curZubie,
        //   },
        // });
        this.props.dispatch({
          type: 'zubie/queryZhixuForChouqian',
          payload: {
            zubieCode: this.props.zubie.curZubie,
          },
        });
      }
    });
  };

  handChouqian = () => {
    if (this.props.zubie.curZubie){
      var path = '/bgms/gameZubie/downloadChouqian/' + this.props.zubie.curZubie;
      if(this.state.curPhase){
        path = path + '?phaseCode=' + this.state.curPhase
      }
      window.open(path, 'GET');
    }
    else
      message.warn("请先选择组别")
  };

  showModifyModal = data => {
    this.setState({
      modalVisible: true,
      curTeamInfo: data,
    });
  };

  handleModalVisible = (flag, datas) => {
    this.setState({
      modalVisible: !!flag,
      curTeamInfo: null,
    });

  };

  modifyTeam = (fields) => {
    const user1 = {
      id: fields.userId1,
      userName: fields.userName1,
      idCard: fields.idCard1,
    }
    fields.athleteList = []
    fields.athleteList.push(user1)

    if (fields.userId2) {
      const user2 = {
        id: fields.userId2,
        userName: fields.userName2,
        idCard: fields.idCard2,
      }
      fields.athleteList.push(user)
    }

    this.props.dispatch({
      type: 'zubie/modifyTeamInfo',
      payload: fields,
      callback: () => {
        this.handleModalVisible(false)
        message.success('人员修改修改成功');
        // this.props.dispatch({
        //   type: 'zubie/queryChouqian',
        //   payload: zhixuParams,
        // });
        this.props.dispatch({
          type: 'zubie/queryZhixuForChouqian',
          payload: {
            zubieCode: this.props.zubie.curZubie,
          },
        });

        const mingdanParams = this.state.mingdanPagination ? this.state.mingdanPagination:{}
        mingdanParams.phaseCode = this.state.curTabPhase
        this.props.dispatch({
          type: 'phase/findPhaseTeam',
          payload: mingdanParams,
        });
      },
    });
  };

  chouqianImport = value => {
    if (value.file.status === 'error') {
      notification.error({
        message: '错误',
        description: value.file.response ? value.file.response.msg : '上传的文件有问题',
      });
    } else if (value.file.status === 'done') {
      message.success('抽签表导入成功');
        // this.props.dispatch({
        //   type: 'zubie/queryChouqian',
        //   payload: zhixuParams,
        // });
      this.props.dispatch({
        type: 'zubie/queryZhixuForChouqian',
        payload: {
          zubieCode: this.props.zubie.curZubie,
        },
      });
      this.props.dispatch({
        type: 'zubie/queryPhase',
        payload: this.props.zubie.curZubie,
        callback: () => {
          const phaseMap = {}
          this.props.zubie.phaseList.map(element => {
            phaseMap[element.code] = element
          })
  
          this.setState({ phaseMap: phaseMap })
        }
      });
      this.props.dispatch({
        type: 'zubie/queryZubieByCode',
        payload: this.props.zubie.curZubie,
      });
      this.props.dispatch({
        type: 'zubie/findPhaseTeam',
        payload: {
          zubieCode: this.props.zubie.curZubie,
        },
      });
    }
  };

  phaseMenu = () => (
    <Menu>
      <Menu.Item key="1">
        <Popconfirm
          title="是否确定使用自动抽签? "
          onConfirm={this.autoChouqian}
          okText="Yes"
          cancelText="No"
        >
          自动抽签
      </Popconfirm>
      </Menu.Item>
      <Menu.Item key="2" onClick={this.handChouqian}>
        下载手动抽签表
      </Menu.Item>
      <Menu.Item key="3">
        <Upload
          action={`/bgms/gameZubie/uploadChouqian/${this.props.zubie.curZubie}?phaseCode=${this.state.curPhase ? this.state.curPhase : null}`}
          name="file"
          disabled={this.props.zubie.curZubie ? false : true}
          showUploadList={false}
          onChange={this.chouqianImport}
        >
          导入抽签表
        </Upload>
      </Menu.Item>
    </Menu>
  )

  downloadFangan = () => {
    if(this.props.zubie.curZubie)
      window.open('/bgms/gameZubie/mingqian/' + this.props.zubie.curZubie, 'GET');
    else
      message.warn("请先选择组别")
  }

  renderSimpleForm() {
    const {
      zubie: { curZubieObj, zubieList, curZubie, phaseList },
    } = this.props;
    return (
      <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
        <Col md={6} sm={24}>
            <Select
              placeholder="请选择组别"
              style={{ width: '100%' }}
              onChange={this.onSelectZubie}
              value={curZubie}
            >
              {zubieList.map(element => {
                if (element.enabled)
                  return <Option key={'OP' + element.code} value={element.code}>
                    {convertProjectCode(element.projectCode) + ' - ' + element.zubieName}
                  </Option>
              })}
            </Select>
        </Col>
        {curZubieObj && curZubieObj.status &&
          curZubieObj.status !== 'NEW' && curZubieObj.status !== 'BC' && <Col md={6} sm={24}>
            <FormItem label="请选择阶段">
              <Select placeholder="未选择" style={{ width: '100%' }} onChange={this.onSelectPhase} value={this.state.curPhase}>
                {phaseList.map(element => (
                  <Option key={'OP' + element.code} value={element.code}>
                    {element.name}
                  </Option>
                ))}
              </Select>
            </FormItem>
          </Col>}
          {!curZubie && 
          <Col md={4} sm={16}>
          <FormItem>
            <Alert style={{flex:1}} message="请选择一个组别" type="error" icon={<Icon type="left" />} showIcon={true}/>
          </FormItem>
          </Col>}

        {curZubieObj && curZubieObj.status &&
          curZubieObj.status === 'NEW' && (
            <Col md={6} sm={24}>
              <Popconfirm
                title="是否确定开始抽签?开始抽签后不能再修改报名和组别信息。 "
                onConfirm={this.beginChouqian}
                okText="Yes"
                cancelText="No"
              >
                <Button type="primary" style={{ marginLeft: 8 }}>
                  开始抽签
                  </Button>
              </Popconfirm>
            </Col>
          )}
        {curZubieObj &&
          curZubieObj.status === 'BC' && (
            <Col md={6} sm={24}>
              <Dropdown overlay={this.phaseMenu()} trigger={['click']}>
                <Button style={{ marginLeft: 8 }}>
                  抽签选项 <Icon type="down" />
                </Button>
              </Dropdown>

            </Col>
          )}{
        }

        <Col md={6} sm={24}>
          <FormItem>
            {this.state.curPhase && this.state.phaseMap && this.state.phaseMap[this.state.curPhase] && this.state.phaseMap[this.state.curPhase].chouqianStatus === 'READY' &&
              <Dropdown overlay={this.phaseMenu(this.state.curPhase)} trigger={['click']}>
                <Button style={{ marginLeft: 8 }}>
                  抽签选项 <Icon type="down" />
                </Button>
              </Dropdown>
            }
            {this.state.curPhase && this.state.phaseMap && this.state.phaseMap[this.state.curPhase] 
            && this.state.phaseMap[this.state.curPhase].chouqianStatus === 'DONE' && !this.state.phaseMap[this.state.curPhase].isFinished &&
            <Tooltip placement="bottomLeft" title="只重置此阶段的抽签数据,包括此阶段的抽签信息和比赛成绩 " arrowPointAtCenter>
              <Popconfirm
                title="是否确定重置?"
                onConfirm={this.cancelPhaseChouqian}
                okText="Yes"
                cancelText="No"
              >
              <Button style={{ marginLeft: 8 }}>
                该阶段重新抽签
              </Button>
              </Popconfirm>
              </Tooltip>
            }
          </FormItem>
        </Col>
        {curZubieObj &&
          (curZubieObj.status === 'AC' || curZubieObj.status === 'BC') && (
            <Col md={6} sm={24}>
            <Tooltip placement="bottomLeft" title="重置后流程将报名重新开始,所有此组别的抽签、比赛、成绩等信息都将丢失且不能找回。如果你只是要替换某个参赛者，请在参赛名单中使用修改参赛人员功能。" arrowPointAtCenter>
              <Popconfirm
                title="是否确定重置此组别数据?请慎重考虑！"
                onConfirm={this.cancelChouqian}
                okText="Yes"
                cancelText="No"
              >
                <Button type="danger" icon="close" style={{ marginLeft: 8 }}>
                  重置组别
                </Button>
              </Popconfirm>
              </Tooltip>
            </Col>
          )}
      </Row>
    );
  }

  renderForm() {
    return this.renderSimpleForm();
  }

  beginChouqian = () => {
    this.props.dispatch({
      type: 'zubie/beginChouqian',
      payload: {
        zubieCode: this.props.zubie.curZubie,
      },
      callback: () => {
        message.info('分组和位置数据已生成，可以开始抽签');
        this.props.dispatch({
          type: 'zubie/queryZhixuForChouqian',
          payload: {
            zubieCode: this.props.zubie.curZubie,
          },
        });
      },
    });
  };

  cancelChouqian = () => {
    this.props.dispatch({
      type: 'zubie/cancelChouqian',
      payload: {
        zubieCode: this.props.zubie.curZubie,
      },
      callback: () => {
        message.success('重置成功')
        this.props.dispatch({
          type: 'zubie/queryPhase',
          payload: this.props.zubie.curZubie,
          callback: () => {
            const phaseMap = {}
            this.props.zubie.phaseList.map(element => {
              phaseMap[element.code] = element
            })
            this.props.dispatch({
              type: 'zubie/queryZhixuForChouqian',
              payload: {
                zubieCode: this.props.zubie.curZubie,
              },
            });
            this.setState({ phaseMap: phaseMap })
          }
        });
      }
    });
  };

  handleTreeQuery =(curPage) =>{
    this.props.dispatch({
      type: 'zubie/queryZhixuForChouqian',
      payload: {
        zubieCode: this.props.zubie.curZubie,
        phaseCode: this.state.curPhase,
        curPage
      },
    });
  }

  cancelPhaseChouqian = () => {
    this.props.dispatch({
      type: 'zubie/cancelPhaseChouqian',
      payload: {
        zubieCode: this.props.zubie.curZubie,
        phaseCode: this.state.curPhase,
      },
      callback: () => {
        message.success('重置抽签成功')
        this.props.dispatch({
          type: 'zubie/queryPhase',
          payload: this.props.zubie.curZubie,
          callback: () => {
            const phaseMap = {}
            this.props.zubie.phaseList.map(element => {
              phaseMap[element.code] = element
            })
            this.props.dispatch({
              type: 'zubie/queryZhixuForChouqian',
              payload: {
                zubieCode: this.props.zubie.curZubie,
              },
            });
            this.setState({ phaseMap: phaseMap })
          }
        });
      }
    });
  };

  handleMingdanChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;

    const params = tableChangePagination(pagination, filtersArg, sorter)
    this.setState({mingdanPagination:JSON.parse(JSON.stringify(params))})
    params.phaseCode = this.state.curTabPhase,

    this.props.dispatch({
      type: 'phase/findPhaseTeam',
      payload: params,
    });
  };

  handleTabChange = (value) => {
    if(value.indexOf('nodata-') !== -1){
      return;
    }

    const titleArray = value.split('_')
    this.setState({
      curTabPhase: titleArray[0]
    })

    if(titleArray.length > 1){
      this.props.dispatch({
        type: 'zubie/changeState',
        payload: {
          zhixuChouqianList:{}
        },
      });
      this.props.dispatch({
        type: 'zubie/queryZhixuForChouqian',
        payload: {
          zubieCode: this.props.zubie.curZubie,
          phaseCode: titleArray[0]
        },
      });
    }else{
      this.props.dispatch({
        type: 'phase/findPhaseTeam',
        payload: {
          phaseCode: titleArray[0],
        },
      });
    }
    
  }

  render() {
    const {
      zubie: { fenzuList, curZubie, curZubieObj, phaseList, zhixuChouqianList, zhixuList },
      phase: {mingdanList},
      loading,
    } = this.props;

    const columns3 = [
      {
        title: '序号',
        key:'index',
        width: 100,
        render: (value, row, index) => <span>{index + 1}</span>,
      },
      {
        title: '抽签号',
        dataIndex:'showCode',
        width: 120,
      },
      {
        title: '所属团队',
        dataIndex: 'teamName',
      },
      {
        title: '种子号',
        dataIndex: 'seedNo',
      },
      {
        title: '对内技术号',
        dataIndex: 'teamNo',
      },
      {
        title: '运动员',
        dataIndex: 'athleteList',
        render: value => value && (
          <span>
            {value.map(value => {
                return value.userName;
              })
              .join(',')}
          </span>
        ),
      },
      {
        title: '操作',
        width: 150,
        key: 'teamAction',
        render: (value, row) => (
          <Fragment key={`fragment${row.id}`} >
            <Button key={`modifyBtn${row.id}`} onClick={() => this.showModifyModal(row)}>修改</Button>
          </Fragment>
        ),
      }
    ];

    const operations = curZubieObj && curZubieObj.status === 'AC' && this.state.curTab === 'nodata-huizongT' && <div>
      <Button type='primary' onClick={this.downloadMingqian}>下载名签</Button>
    </div>

    return (
      <Fragment>
        <Card>
          <div className={styles.tableList}>
            <div className={styles.tableListForm}>{this.renderForm()}</div>
            {curZubieObj && (
              <Tabs onChange={this.handleTabChange}>
                {phaseList.map(element => (
                <TabPane
                  tab={element.name+'抽签表'}
                  key={element.code + '_' + element.lastPhase+'_' +element.gameMethod}
                  forceRender={true}
                >
                  {zhixuChouqianList && zhixuChouqianList.gameMethod && ((zhixuChouqianList.gameMethod === 'CYCLE' || zhixuChouqianList.gameMethod === 'FENZU')
                    ? generateChouqianTable(null,zhixuChouqianList.list)
                    : generateTreeTable(null, zhixuChouqianList, this.handleTreeQuery))}
                </TabPane>
              ))}
                {phaseList.map(element => (
                  <TabPane
                    tab={element.name+'-名单'}
                    key={element.code}
                  >
                      <Table
                      loading={loading}
                      dataSource={mingdanList.list}
                      pagination={mingdanList.pagination}
                      columns={columns3}
                      bordered
                      size='small'
                    //onSelectRow={this.handleSelectRows}
                    onChange={this.handleMingdanChange}
                    />
                  </TabPane>
                ))}
              </Tabs>
            )}
          </div>
        </Card>
        <TeamInfoForm
          handleModalVisible={this.handleModalVisible}
          handleAdd={this.modifyTeam}
          modalVisible={this.state.modalVisible}
          curData={this.state.curTeamInfo}
        />
      </Fragment>
    );
  }
}
